package com.sgb.kjwl.view.ui.fragment.home;

import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.sgb.alimaplibrary.util.ToastUtil;
import com.sgb.kjwl.BaseHeightViewPagerFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentEngineeringteamJobHuntingBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.BannerEntity;
import com.sgb.kjwl.model.entity.BiddingEntity;
import com.sgb.kjwl.model.entity.EmploymentEntity;
import com.sgb.kjwl.model.entity.FindPackersEntity;
import com.sgb.kjwl.model.entity.FindPeopleEntity;
import com.sgb.kjwl.model.entity.packers.LaborWorkMomentDetailEntity;
import com.sgb.kjwl.model.entity.packers.LabourServiceAndEmploymentEntity;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.view.ui.activity.packers.LaborServiceAndEmploymentDetailActivity;
import com.sgb.kjwl.view.ui.adapter.packers.LaborServiceAndEmploymentAdapter;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.TeamPriceItemEntity;
import com.sgb.kjwl.model.entity.packers.EngineeringCompanyEntity;
import com.sgb.kjwl.view.event.CategoryEvent2;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.manage.WebsiteInfoActivity;
import com.sgb.kjwl.view.ui.activity.packers.EmploymentDetailActivity;
import com.sgb.kjwl.view.ui.activity.packers.TeamOfferDetailActivity;
import com.sgb.kjwl.view.ui.adapter.LookingforAJob.FindWorksAdapter;
import com.sgb.kjwl.view.ui.adapter.packers.EngineeringCompanyAdapter;
import com.sgb.kjwl.view.ui.adapter.packers.FindPackersAdapter;
import com.sgb.kjwl.view.ui.adapter.packers.FindPeopleAdapter;
import com.sgb.kjwl.view.ui.adapter.packers.PackersEmploymentAdapter;
import com.sgb.kjwl.view.ui.adapter.pick.PickBidingAdapter;
import com.sgb.kjwl.view.ui.adapter.price.QuotePriceListAdapter;
import com.sgb.kjwl.view.widget.HomeGoodsSelectionTypePopWindow;
import com.sgb.kjwl.viewmodel.home.EngineeringTeamJobHuntingModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;


/**
 * 工队服务中的找活干fragment
 */
public class EngineeringTeamJobHuntingFragment extends BaseHeightViewPagerFragment {

    @Inject
    EngineeringTeamJobHuntingModel viewModel;
    private FragmentEngineeringteamJobHuntingBinding binding;
    private int mItemType;

    private List<PickSelectEntity> mTabEntityData;
    private PickSelectEntity mCategory = new PickSelectEntity("", "全部");
    //招工用工适配器
    private PackersEmploymentAdapter packersEmploymentAdapter;
    //工种报价
    private QuotePriceListAdapter quotePriceListAdapter;
    //施工队  班组工队 适配器
    private FindPackersAdapter findPackersAdapter;
    // 工程工队
    private EngineeringCompanyAdapter engineeringCompanyAdapter;
    private FindWorksAdapter jobsAdapter;
    private FindPeopleAdapter workerAdapter;
    private PickBidingAdapter pickingAdapter;
    //劳务用工
    private LaborServiceAndEmploymentAdapter employmentAdapter;
    private ArrayList<PickSelectEntity> typeList = new ArrayList();

    private HomeGoodsSelectionTypePopWindow mPopWindow;

    public static EngineeringTeamJobHuntingFragment newInstance(int position, BannerEntity bannerEntity, boolean isRefresh) {
        EngineeringTeamJobHuntingFragment fragment = new EngineeringTeamJobHuntingFragment();
        Bundle args = new Bundle();
        //当前的目录名字
        args.putSerializable(ARG_PARAM, bannerEntity);
        //当前的下标
        args.putInt(ARG_PARAM_POS, position);
        //刷新字段
        args.putBoolean(ARG_isRefresh, isRefresh);
        fragment.setArguments(args);
        return fragment;
    }

    private int getItemType() {
        int mItemType = -1;
        //获取当前目录名字
        BannerEntity bannerEntity = (BannerEntity) getArguments().getSerializable(ARG_PARAM);
        //判断符合对象
        switch (bannerEntity.getName()) {
            case "劳务分包":
                mItemType = 1;
                break;
            case "找工人":
                mItemType = 2;
                break;
            case "工种报价":
                mItemType = 3;
                break;
            case "招工用工":
                mItemType = 4;
                break;
            case "施工队":
                mItemType = 5;
                break;
            case "班组":
                mItemType = 6;
                break;
            case "工程公司":
                mItemType = 7;
                break;
            case "劳务用工":
                mItemType = 8;
                break;
        }
        return mItemType;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(getActivity())) {
            EventBus.getDefault().register(getActivity());
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_engineeringteam_job_hunting, container, false);
        return binding.getRoot();

    }

    @Override
    protected void initView() {
        super.initView();
        if (getArguments() == null) {
            return;
        }
        mItemType = getItemType();
        if (mItemType == -1) {
            return;
        }
        //设置tab的模式为可滑动
        binding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        //recycler设置禁止嵌套，防止滑动冲突
        binding.recycler.setNestedScrollingEnabled(false);
        //recycler设置布局管理为线性垂直，每行默认显示一个item
        binding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));
        //recycler设置装饰
        //binding.recycler.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.dp1);
            }
        });
        /*binding.recycler.addItemDecoration(new RecyclerView.ItemDecoration(){
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = getResources().getDimensionPixelSize(R.dimen.dp1);
            }
        });*/
        switch (mItemType) {
            case 1://劳务分包
                //劳务分包适配器
                pickingAdapter = new PickBidingAdapter(getActivity(), null);
                pickingAdapter.setOnItemClick(new AdapterOnItemClick<BiddingEntity>() {
                    @Override
                    public void onItemClick(BiddingEntity biddingEntity, int position) {
                        viewModel.getUrlSetting(biddingEntity.getId());
                    }
                });
                pickingAdapter.onIChildClick(new PickBidingAdapter.IChildClick() {
                    @Override
                    public void onClick(BiddingEntity tenderListEntity) {
                        viewModel.getUrlSetting(tenderListEntity.getId());
                    }
                });
                /*jobsAdapter = new FindWorksAdapter(getActivity(), null);
                //适配器点击事件
                jobsAdapter.setOnItemClick(new AdapterOnItemClick<FindJobEntity>() {
                    @Override
                    public void onItemClick(FindJobEntity findJobEntity, int position) {
                        // 跳转URL
                        // viewModel.getH5Url(findJobEntity.getNo());
                        //企业类型0:个人1:企业
                        if (findJobEntity.getIsCompany() == 0) {
                            // String s = DateUtils.timestampToDate(findJobEntity.getCreateTime());
                            PersonShopActivity.start(getActivity(), findJobEntity.getNo(), findJobEntity.getUserNo(), findJobEntity.getCreateTime(), "");
                        } else {
                            if (TextUtils.isEmpty(findJobEntity.getCompanyId())) {
                                ToastUtil.show(getActivity(), "企业店铺id不能为空");
                                return;
                            }
                            WebsiteInfoActivity.start(getActivity(), findJobEntity.getNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
                        }
                    }
                });*/
                //recycler设置适配器
                binding.recycler.setAdapter(pickingAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 2://找工人
                //找工人的适配器
                workerAdapter = new FindPeopleAdapter(getActivity(), null, Glide.with(this));
                //适配器的点击事件
                workerAdapter.setOnItemClick(new AdapterOnItemClick<FindPeopleEntity>() {
                    @Override
                    public void onItemClick(FindPeopleEntity findPeopleEntity, int position) {
                        //跳转到H5的详情届面
                        viewModel.getH5Url(findPeopleEntity.getNo(), "workerDetails");
                    }
                });
                //recycler设置适配器
                binding.recycler.setAdapter(workerAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 3://工种报价
                //工种报价适配器
                quotePriceListAdapter = new QuotePriceListAdapter(getActivity(), null);
                // 适配器点击事件
                quotePriceListAdapter.setOnItemClick(new AdapterOnItemClick<TeamPriceItemEntity>() {
                    @Override
                    public void onItemClick(TeamPriceItemEntity teamPriceItemEntity, int position) {
               /* if (teamPriceItemEntity.isCompany()) {
                    PersonShopActivity.start(getActivity(), teamPriceItemEntity.getUserNo(), teamPriceItemEntity.getCreateTime());
                } else {
                    ShopInfoActivity.start(getActivity(), teamPriceItemEntity.getCompanyId(), 4);
                }*/
                        TeamOfferDetailActivity.start(getActivity(), teamPriceItemEntity.getNo());
                    }
                });
                //recycler设置适配器
                binding.recycler.setAdapter(quotePriceListAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 4://招工用工
                //招工用工适配器
                packersEmploymentAdapter = new PackersEmploymentAdapter(getActivity(), null, true);
                // 适配器点击事件
                packersEmploymentAdapter.setOnItemClick(new AdapterOnItemClick<EmploymentEntity>() {
                    @Override
                    public void onItemClick(EmploymentEntity employmentEntity, int position) {
                        EmploymentDetailActivity.start(getContext(), employmentEntity.getNo(), employmentEntity.getProjectName(), employmentEntity.isIsApply());
                    }
                });
                //recycler设置适配器
                binding.recycler.setAdapter(packersEmploymentAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 5://施工队  班组工队 :数据源相同,适配器相同，实现共用
            case 6:
                if (mItemType == 5) {
                    findPackersAdapter = new FindPackersAdapter(getActivity(), null, Glide.with(this), true, true);
                } else {
                    findPackersAdapter = new FindPackersAdapter(getActivity(), null, Glide.with(this), false, true);
                }
                //适配器点击事件
                findPackersAdapter.setOnItemClick(new AdapterOnItemClick<FindPackersEntity>() {
                    @Override
                    public void onItemClick(FindPackersEntity findPackersEntity, int position) {
                        viewModel.getH5Url(findPackersEntity.getNo(), "teamWorkDetail");
                    }
                });
                //recycler设置适配器
                binding.recycler.setAdapter(findPackersAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
            case 7:
                //创建适配器对象
                engineeringCompanyAdapter = new EngineeringCompanyAdapter(getActivity(), null, Glide.with(this));
                //适配器点击事件
                engineeringCompanyAdapter.setOnItemClick(new AdapterOnItemClick<EngineeringCompanyEntity>() {
                    @Override
                    public void onItemClick(EngineeringCompanyEntity entity, int position) {
                        if (TextUtils.isEmpty(entity.getId())) {
                            ToastUtil.show(getActivity(), "企业店铺id不能为空");
                            return;
                        }
                        WebsiteInfoActivity.start(getActivity(), entity.getCompanyNo(), WebsiteInfoActivity.WEBSITE_FOR_COMPANY);
                    }
                });
                //recycler设置适配器
                binding.recycler.setAdapter(engineeringCompanyAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.GONE);
                break;
            case 8:
                employmentAdapter = new LaborServiceAndEmploymentAdapter(getActivity(), null);
                employmentAdapter.setOnItemClick(new AdapterOnItemClick<LabourServiceAndEmploymentEntity>() {
                    @Override
                    public void onItemClick(LabourServiceAndEmploymentEntity labourServiceAndEmploymentEntity, int position) {
                        viewModel.getLaborWorkDetail(labourServiceAndEmploymentEntity);
                    }
                });
                //recycler设置适配器
                binding.recycler.setAdapter(employmentAdapter);
                //tab布局设置隐藏
                binding.llTabLayout.setVisibility(View.VISIBLE);
                break;
        }
        binding.tvMore.setOnClickListener(v -> loadData(true));
        binding.tvGoModel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 5));
            }
        });
        binding.tvGoModel1.setOnClickListener(v -> EventBus.getDefault().postSticky(CategoryEvent2.make(EventConstant.EVENT_CATEGORY_CHOOSE2, 5)));
    }

    @Override
    public void IsRefresh(boolean isRefresh) {
        setIsRefresh(isRefresh);
        loadData(false);
    }

    @Override
    protected void onLazyLoad() {
        switch (mItemType) {
            case 1:
                //劳务分包
                viewModel.getTenderGoodsCategoryAllList();
                break;
            case 2:
                //找工人
                viewModel.getLinkAgeWorkType();
                break;
            //请求分类接口
            case 3:
                //工种报价
                viewModel.getEngineeringType(mItemType);
                break;
            case 4:
                //招工用工
                viewModel.getProTypeList(mItemType);
                break;
            case 5:
            case 6:
                viewModel.getCategoryType(mItemType);
                break;
            case 7:
                viewModel.getCompanyCategoryType();
                break;
            case 8:
                viewModel.getLinkAgeType();
                break;
            default:
                break;
        }
        //由于不显示二级栏目故直接加载列表数据
        loadData(false);
    }


    @Override
    public void onVisible() {
        super.onVisible();
        loadData(false);
    }

    private void loadData(boolean isLoadMore) {
        switch (mItemType) {
            case 1://劳务分包
                viewModel.getBiddingList(mCategory.getNo(), isLoadMore, getPosition(), mItemType, getIsRefresh());
                break;
            case 2://找工人
                viewModel.getWorkList("", mCategory.getNo(), isLoadMore, getPosition(), mItemType, getIsRefresh());
                break;
            case 3://工种报价
                viewModel.getWorkQuotationList(mCategory.getNo(), getPosition(), isLoadMore, mItemType, getIsRefresh());
                break;
            case 4://招工用工
                viewModel.getEmploymentList(mCategory.getNo(), getPosition(), isLoadMore, mItemType, getIsRefresh());
                break;
            case 5://施工队
                viewModel.getTeamList("0", mCategory.getNo(), getPosition(), isLoadMore, mItemType, getIsRefresh());
                break;
            case 6://班组
                viewModel.getTeamList("1", mCategory.getNo(), getPosition(), isLoadMore, mItemType, getIsRefresh());
                break;
            case 7://工程公司
                viewModel.getConstructionTeamList("2", mCategory.getNo(), getPosition(), isLoadMore, mItemType, getIsRefresh());
                break;
            case 8://劳务用工
                viewModel.getLabourList(mCategory.getNo(), getPosition(), isLoadMore, mItemType, getIsRefresh());
                break;
        }
    }

    /**
     * 分类数据
     *
     * @param datas
     * @param <T>
     */
    public <T> void setTypeDatas(List<T> datas) {
        //判断是否为空
        if (datas == null || datas.size() == 0) {
            //为空则隐藏tab布局，显示省缺界面
            binding.tabLayout.setVisibility(View.GONE);
            binding.emptyView.setVisibility(View.VISIBLE);
            return;
        }
        //显示tab布局
        binding.tabLayout.setVisibility(View.VISIBLE);
        //添加特定entity为第一位
        datas.add(0, (T) mCategory);
        switch (mItemType) {
            case 1://劳务分包
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
            case 7:
            case 8:
                //强转list
                List<PickSelectEntity> mTypeList = (List<PickSelectEntity>) datas;
                //清空存储的type集合,保证数据的最新状态
                typeList.clear();
                //存储最新的type数据
                typeList.addAll(mTypeList);
                //遍历分类集合
                for (int i = 0; i < typeList.size(); i++) {
                    //创建tab子类对象
                    binding.tabLayout.addTab(binding.tabLayout.newTab().setText(typeList.get(i).getProjectscale()));
                }
                //设置tab的点击改变监听事件
                binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

                    @Override
                    public void onTabSelected(TabLayout.Tab tab) {
                        //当前选中的分类发生改变时，改变的item将改变默认值
                        mCategory = mTypeList.get(tab.getPosition());
                        //重新网络请求
                        loadData(false);
                    }

                    @Override
                    public void onTabUnselected(TabLayout.Tab tab) {
                    }

                    @Override
                    public void onTabReselected(TabLayout.Tab tab) {

                    }
                });
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + mItemType);
        }
    }

    //展示列表的封装方法，根据相应的mItemType进行强转，设置适配器，刷新数据
    public <T> void showList(List<T> list, boolean isLoadMore) {
        switch (mItemType) {
            case 1:
                List<BiddingEntity> list1 = (List<BiddingEntity>) list;
                updateData(pickingAdapter, list1, isLoadMore);
                break;
            case 2:
                List<FindPeopleEntity> list2 = (List<FindPeopleEntity>) list;
                updateData(workerAdapter, list2, isLoadMore);
                break;
            case 3:
                List<TeamPriceItemEntity> list3 = (List<TeamPriceItemEntity>) list;
                updateData(quotePriceListAdapter, list3, isLoadMore);
                break;
            case 4:
                List<EmploymentEntity> list4 = (List<EmploymentEntity>) list;
                updateData(packersEmploymentAdapter, list4, isLoadMore);
                break;
            case 5:
            case 6:
                List<FindPackersEntity> list5 = (List<FindPackersEntity>) list;
                updateData(findPackersAdapter, list5, isLoadMore);
                break;
            case 7:
                List<EngineeringCompanyEntity> list7 = (List<EngineeringCompanyEntity>) list;
                updateData(engineeringCompanyAdapter, list7, isLoadMore);
                break;
            case 8:
                List<LabourServiceAndEmploymentEntity> list8 = (List<LabourServiceAndEmploymentEntity>) list;
                updateData(employmentAdapter, list8, isLoadMore);
                break;
        }
    }

    //更新数据
    public <T> void updateData(BaseRecycleAdapter<T> adapter, List<T> list, boolean isLoadMore) {
        //判断是否加载更多
        if (isLoadMore) {
            //判断列表数据是否为空
            if (list != null && list.size() > 0) {
                //适配器设置数据
                adapter.addDatas(list);
                if (list.size() < 3) {
                    //当数据少于3个时，隐藏加载更多按钮
                    binding.lineMore.setVisibility(View.VISIBLE);
                    binding.tvMore.setVisibility(View.GONE);
                } else {
                    //当数据数量正常时，默认显示加载更多按钮
                    binding.lineMore.setVisibility(View.VISIBLE);
                }
            } else {
                //当数据返回为空时，隐藏加载更多按钮
                binding.lineMore.setVisibility(View.VISIBLE);
                binding.tvMore.setVisibility(View.GONE);
            }
        } else {
            //判断列表数据是否为空
            if (list != null && list.size() > 0) {
                //当有数据时，显示加载更多按钮，隐藏缺省界面
                binding.lineMore.setVisibility(View.VISIBLE);
                if (list.size() < 3) {
                    //当数据少于3个时，隐藏加载更多按钮
                    binding.tvMore.setVisibility(View.GONE);
                } else {
                    binding.tvMore.setVisibility(View.VISIBLE);
                }
                binding.emptyView.setVisibility(View.GONE);
            } else {
                //当有数据时，隐藏加载更多按钮，显示缺省界面
                binding.lineMore.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
            //适配器设置数据
            adapter.setDatas(list);
        }
    }


    public <T> void loadCacheData(BaseRecycleAdapter<T> adapter) {
        List<T> data = adapter.getDatas();
        if (data != null && data.size() > viewModel.mPageSize) {
            List<T> tempList = new ArrayList<>();
            tempList.add(data.get(0));
            tempList.add(data.get(1));
            tempList.add(data.get(2));
            adapter.setDatas(tempList);
            //重新设置页数
            viewModel.mPageIndex = 1;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void setLaborWorkDetail(LaborWorkMomentDetailEntity entity, LabourServiceAndEmploymentEntity data) {
        if (entity.getIsEnable() == 0) {
            MToast.showToast(getActivity(),"该劳务用工已招满，请重新选择");
        }else {
            ActivityJump.jumpToActivityForResult(getActivity(), LaborServiceAndEmploymentDetailActivity.class,0, Pair.create("no",data.getNo()),Pair.create("workNo",data.getWorkNo()),Pair.create("workName",data.getCategoryName()),Pair.create("isFocus",data.getIsFocus()),Pair.create("isApply",data.isApply()),Pair.create("mMomentNo",data.getUserNo()),Pair.create("workNameForList",data.getWorkName()),Pair.create("employmentType",data.getEmploymentType()),Pair.create("imId",data.getImId()));
        }
    }
}
